package francis.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import francis.model.VideoInfo;

/**
 * 视频的一些工具方法
 * @author francis  started at 2011-11-22
 *
 */
public class VideoUtil {
	
	/**
	 * 
	 * @param url 例: http://api.bilibili.tv/list?type=xml&tid=19
	 * @return
	 */
	public static List<VideoInfo> getVideoInfos(String url) {
		
		List<VideoInfo> vInfos = new ArrayList<VideoInfo>();
		
		Document doc = WebTools.getWebContent(url);
		//获取data结点
		@SuppressWarnings("unchecked")
		List<Element> eles = doc.selectNodes("//data");
		
		for(Element ele : eles) {
			vInfos.add(VideoUtil.getVideoInfo(ele));
		}
		
		return vInfos;
	}

	
	public static VideoInfo getVideoInfo(Element ele) {
		
		Map<String,String> key_value = new HashMap<String,String>();
		@SuppressWarnings("unchecked")
		List<Element> attrs = ele.elements();
    	for(Element attr: attrs) {
    		key_value.put(attr.getName().trim(), attr.getText().trim());
    	}
    	
    	VideoInfo vi = new VideoInfo(key_value);
		
		return vi;
	}
	/**
	 * http://api.bilibili.tv/view?id=171198&type=xml
	 * @param aid
	 * @return
	 */
	public static VideoInfo getVideoInfo(String aid,int page) {
		
		String url = "http://api.bilibili.tv/view?id=" + aid + "&&type=xml&&page=" +  page;
		Document doc = WebTools.getWebContent(url);
		
		Element ele = (Element) doc.selectNodes("//info").get(0);
		return getVideoInfo(ele);
		
	}
	
	public static VideoInfo getVideoInfo(String aid) {
		return getVideoInfo(aid,1);
	}
}
